<template>
  <el-dialog
    v-model="visible"
    title="报表统计"
    width="85%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="report-dialog"
    destroy-on-close
  >
    <div class="report-container">
      <!-- 查询条件 -->
      <div class="query-section">
        <el-form :model="queryForm" inline>
          <el-form-item label="时间类型">
            <el-select v-model="queryForm.timeType" placeholder="请选择时间类型" style="width: 150px;">
              <el-option label="分钟数据" value="2051" />
              <el-option label="小时数据" value="2061" />
              <el-option label="日数据" value="2031" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="queryForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 350px;"
              :shortcuts="dateShortcuts"
              :clearable="false"
              :disabled-date="disabledDate"
              @change="handleTimeRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-radio-group v-model="viewType" @change="handleViewChange">
              <el-radio-button label="table">表格视图</el-radio-button>
              <el-radio-button label="chart">图表视图</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="margin-left: 15px;">
            <el-button 
              type="success" 
              @click="handleExport" 
              :loading="exportLoading"
              :disabled="tableData.length === 0"
            >
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格视图 -->
      <div v-if="viewType === 'table'" class="table-section">
        
        <el-table
          :data="tableData"
          height="500"
          v-loading="loading"
          show-summary
          :summary-method="getSummaries"
          style="width: 100%;--el-table-border-color: rgba(255,255,255,0.1);"
        >
          <el-table-column type="index" label="序号" width="120" align="center" :index="indexMethod" />
          <el-table-column prop="所属单位" label="所属单位" min-width="160" align="center" />
          <el-table-column prop="监测时间" label="监测时间" min-width="180" align="center" />
          <el-table-column prop="污水流量" label="污水流量(m³)" min-width="120" align="center" />
          <el-table-column prop="流量均值" label="流量均值(L/s)" min-width="120" align="center" />
          <el-table-column prop="PH值" label="PH值(无量纲)" min-width="120" align="center" />
          <el-table-column prop="化学需氧量COD" label="化学需氧量COD" min-width="120" align="center" />
          <el-table-column prop="总余氯" label="总余氯" min-width="120" align="center" />
          <el-table-column prop="氨氮" label="氨氮" min-width="120" align="center" />
        </el-table>
        <!-- 总记录数显示 -->
        <div class="table-footer">
          <span class="total-count">共 {{ tableData.length }} 条记录</span>
        </div>
      </div>

      <!-- 图表视图 -->
      <div v-if="viewType === 'chart'" class="chart-section">
        <div ref="chartRef" style="width: 100%; height: 500px;"></div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElDialog, ElForm, ElFormItem, ElSelect, ElOption, ElDatePicker, ElButton, ElIcon, ElTable, ElTableColumn, ElRadioGroup, ElRadioButton, ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { getHospitalSensorData, exportHospitalSensorData } from '@/api/h3yun'
import * as echarts from 'echarts'

// 定义props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  unitId: {
    type: String,
    default: ''
  }
})

// 定义emits
const emit = defineEmits(['update:modelValue'])

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const exportLoading = ref(false)
const viewType = ref('table')
const tableData = ref([])
const chartRef = ref()
let chartInstance: echarts.ECharts | null = null

// 查询表单
const queryForm = reactive({
  timeType: '2061',
  timeRange: []
})

// 时间快捷选项
const dateShortcuts = [
  {
    text: '最近1小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(start.getHours() - 1)
      return [start, end]
    }
  },
  {
    text: '最近6小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(start.getHours() - 6)
      return [start, end]
    }
  },
  {
    text: '最近24小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(start.getHours() - 24)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 30)
      return [start, end]
    }
  }
]

// 本地时间格式化函数
const formatLocalTime = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 初始化时间范围（根据时间类型设置不同的默认范围）
const initTimeRange = () => {
  const end = new Date()
  const start = new Date()
  
  switch (queryForm.timeType) {
    case '2051': // 分钟数据 - 默认今日
      start.setHours(0, 0, 0, 0)
      break
    case '2061': // 小时数据 - 默认最近3天
      start.setDate(start.getDate() - 3)
      break
    case '2031': // 日数据 - 默认最近30天
      start.setDate(start.getDate() - 30)
      break
    default:
      start.setDate(start.getDate() - 7)
  }
  
  queryForm.timeRange = [
    formatLocalTime(start),
    formatLocalTime(end)
  ]
}

// 禁用日期函数（分钟数据最多只能选择最近3天）
const disabledDate = (time: Date) => {
  if (queryForm.timeType === '2051') {
    const threeDaysAgo = new Date()
    threeDaysAgo.setDate(threeDaysAgo.getDate() - 3)
    return time.getTime() < threeDaysAgo.getTime()
  }
  return false
}

// 时间范围变化处理
const handleTimeRangeChange = (value: any) => {
  if (!value || value.length !== 2) {
    // 如果时间范围被清空，重新设置默认值
    initTimeRange()
  }
}

// 查询数据
const handleQuery = async () => {
  if (!queryForm.timeRange || queryForm.timeRange.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }

  loading.value = true
  try {
    const params = {
      cn: queryForm.timeType,
      areaCode: props.unitId,
      startTime: queryForm.timeRange[0],
      endTime: queryForm.timeRange[1]
    }

    const result = await getHospitalSensorData(params)
    
    if (result.code === '0' && result.data) {
      // 对数据进行排序，最新数据在前（表格视图）或右侧（图表视图）
      const sortedData = result.data.sort((a: any, b: any) => {
        const timeA = new Date(a['监测时间']).getTime()
        const timeB = new Date(b['监测时间']).getTime()
        return timeB - timeA // 降序排列，最新时间在前
      })
      
      tableData.value = sortedData
      if (viewType.value === 'chart') {
        nextTick(() => {
          renderChart()
        })
      }
    } else {
      ElMessage.error(result.msg || '查询失败')
    }
  } catch (error) {
    console.error('查询数据失败:', error)
    ElMessage.error('查询数据失败')
  } finally {
    loading.value = false
  }
}

// 重置查询条件
const handleReset = () => {
  queryForm.timeType = '2061'
  initTimeRange()
  handleQuery() // 重置后自动查询
}

// 导出数据
const handleExport = async () => {
  if (!queryForm.timeRange || queryForm.timeRange.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }

  if (tableData.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }

  exportLoading.value = true
  try {
    const params = {
      cn: queryForm.timeType,
      areaCode: props.unitId,
      startTime: queryForm.timeRange[0],
      endTime: queryForm.timeRange[1]
    }

    const result = await exportHospitalSensorData(params)
    
    // axios返回的数据在result.data中
    const blob = new Blob([result.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名
    const timeTypeText = queryForm.timeType === '2051' ? '分钟数据' : 
                        queryForm.timeType === '2061' ? '小时数据' : '日数据'
    const startDate = queryForm.timeRange[0].split(' ')[0]
    const endDate = queryForm.timeRange[1].split(' ')[0]
    link.download = `污水处理监测数据_${timeTypeText}_${startDate}_${endDate}.xlsx`
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  } finally {
    exportLoading.value = false
  }
}

// 视图切换
const handleViewChange = (type: string) => {
  if (type === 'chart' && tableData.value.length > 0) {
    nextTick(() => {
      renderChart()
    })
  }
}

// 渲染图表
const renderChart = () => {
  if (!chartRef.value || tableData.value.length === 0) return

  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  // 对数据进行时间排序（升序，最新数据在右侧）
  const sortedData = [...tableData.value].sort((a: any, b: any) => {
    const timeA = new Date(a['监测时间']).getTime()
    const timeB = new Date(b['监测时间']).getTime()
    return timeA - timeB // 升序排列，最新时间在右侧
  })

  const times = sortedData.map(item => item['监测时间'])
  const codData = sortedData.map(item => item['化学需氧量COD'] || 0)
  const flowData = sortedData.map(item => item['污水流量'] || 0)
  const flowAvgData = sortedData.map(item => item['流量均值'] || 0)
  const phData = sortedData.map(item => item['PH值'] || 0)
  const chlorideData = sortedData.map(item => item['总余氯'] || 0)
  const ammoniaData = sortedData.map(item => item['氨氮'] || 0)

  // 时间格式化函数
  const formatTime = (timeStr: string) => {
    if (!timeStr) return ''
    
    const date = new Date(timeStr)
    const timeType = queryForm.timeType
    
    switch (timeType) {
      case '2051': // 分钟数据
        return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
      case '2061': // 小时数据
        return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:00`
      case '2031': // 日数据
        return `${date.getMonth() + 1}-${date.getDate()}`
      default:
        return timeStr
    }
  }

  const formattedTimes = times.map(formatTime)

  const option = {
    title: {
      text: '污水处理监测数据统计',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['污水流量(m³)', '流量均值(L/s)', 'PH值(无量纲)', '化学需氧量COD', '总余氯', '氨氮'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: 0,
        end: 100,
        bottom: 10,
        height: 20
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: formattedTimes,
      axisLabel: {
        rotate: 45,
        fontSize: 12,
        interval: 'auto',
        formatter: function(value: string) {
          // 如果标签太长，进行截断
          if (value.length > 10) {
            return value.substring(0, 10) + '...'
          }
          return value
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '',
        nameTextStyle: {
          color: '#333',
          fontSize: 12
        },
        axisLabel: {
          fontSize: 12,
          formatter: function(value: number) {
            return value.toFixed(2)
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#ddd'
          }
        }
      },
      {
        type: 'value',
        name: '其他指标',
        nameTextStyle: {
          color: '#333',
          fontSize: 12
        },
        axisLabel: {
          fontSize: 12,
          formatter: function(value: number) {
            return value.toFixed(2)
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '污水流量(m³)',
        type: 'line',
        smooth: true,
        data: flowData,
        itemStyle: {
          color: '#91cc75'
        },
        lineStyle: {
          width: 3
        },
        yAxisIndex: 0
      },
      {
        name: '流量均值(L/s)',
        type: 'line',
        smooth: true,
        data: flowAvgData,
        itemStyle: {
          color: '#9a60b4'
        },
        lineStyle: {
          width: 3
        },
        yAxisIndex: 0
      },
      {
        name: 'PH值(无量纲)',
        type: 'line',
        smooth: true,
        data: phData,
        itemStyle: {
          color: '#fac858'
        },
        lineStyle: {
          width: 3
        },
        yAxisIndex: 1
      },
      {
        name: '化学需氧量COD',
        type: 'line',
        smooth: true,
        data: codData,
        itemStyle: {
          color: '#5470c6'
        },
        lineStyle: {
          width: 3
        },
        yAxisIndex: 1
      },
      {
        name: '总余氯',
        type: 'line',
        smooth: true,
        data: chlorideData,
        itemStyle: {
          color: '#ee6666'
        },
        lineStyle: {
          width: 3
        },
        yAxisIndex: 1
      },
      {
        name: '氨氮',
        type: 'line',
        smooth: true,
        data: ammoniaData,
        itemStyle: {
          color: '#73c0de'
        },
        lineStyle: {
          width: 3
        },
        yAxisIndex: 1
      }
    ]
  }

  chartInstance.setOption(option)
}

// 监听时间类型变化
watch(() => queryForm.timeType, (newType) => {
  initTimeRange()
  handleQuery() // 时间类型变化后自动查询
})

// 监听弹窗显示状态
watch(visible, (newVal) => {
  if (newVal) {
    initTimeRange()
    handleQuery()
  }
})

// 组件挂载时初始化
onMounted(() => {
  initTimeRange()
  handleQuery() // 组件挂载时自动查询
})

// 组件卸载时清理图表实例
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 自定义合计函数
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = ''
      return
    }
    
    if (column.property === '污水流量') {
      const values = data.map((item: any) => Number(item[column.property]) || 0)
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toFixed(2)
        sums[index] = '合计：' + sums[index]
      } else {
        sums[index] = '0.00'
      }
    } else if (column.property === '流量均值' || column.property === 'PH值') {
      const values = data.map((item: any) => Number(item[column.property]) || 0)
      if (!values.every(value => isNaN(value))) {
        const avg = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0) / values.filter(v => !isNaN(v)).length
        sums[index] = column.property === '流量均值' ? avg.toFixed(2) : avg.toFixed(4)
        sums[index] = '均值：' + sums[index]
      } else {
        sums[index] = '0.00'
      }
    } else {
      sums[index] = ''
    }
  })
  
  return sums
}

// 序号列的索引方法
const indexMethod = (index: number) => {
  return index + 1
}
</script>

<style scoped lang="scss">
.report-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    height: 85vh;
    z-index: 9999 !important;
    
    .el-dialog__header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 8px 8px 0 0;
      
      .el-dialog__title {
        color: white !important;
        font-weight: bold;
      }
      
      .el-dialog__headerbtn .el-dialog__close {
        color: white;
      }
    }
    
    .el-dialog__body {
      height: calc(85vh - 120px);
      overflow-y: auto;
    }
  }
  
  // 确保遮罩层也有足够高的z-index
  :deep(.el-overlay) {
    z-index: 9998 !important;
  }
}

.report-container {
  padding: 10px 20px 20px 20px;
}

.query-section {
  background: transparent;
  padding: 10px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  color: #fff;
  
  .el-form-item {
    margin-bottom: 0;
    
    :deep(.el-form-item__label) {
      color: #fff;
      font-weight: bold;
      font-size: 14px;
    }
    
    :deep(.el-select .el-input__wrapper) {
      background: white;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
    }
    
    :deep(.el-date-editor .el-input__wrapper) {
      background: white;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
    }
    
    :deep(.el-date-editor .el-input__inner) {
      color: white !important;
    }
    
    :deep(.el-date-editor .el-range-input) {
      color: white !important;
    }
    
    :deep(.el-date-editor .el-range-separator) {
      color: white !important;
    }
    
    // 添加时间范围图标颜色为白色
    :deep(.el-date-editor .el-range__icon) {
        color: white !important;
    }
    
    :deep(.el-button) {
      background: white;
      border: 1px solid #dcdfe6;
      color: #606266;
      font-weight: bold;
      border-radius: 6px;
      
      &:hover {
        background: #f5f7fa;
        color: #409eff;
        border-color: #c6e2ff;
      }
      
      &.el-button--primary {
        background: #409eff;
        color: white;
        border-color: #409eff;
        
        &:hover {
          background: #66b1ff;
          border-color: #66b1ff;
        }
      }
      
      &.el-button--success {
        background: #67c23a;
        border-color: #67c23a;
        color: white;
        
        &:hover {
          background: #85ce61;
          border-color: #85ce61;
        }
        
        &:disabled {
          background: #c2c2c2;
          border-color: #c2c2c2;
          color: #999;
        }
      }
    }
  }
}

.table-section {
  .el-table {
    border-radius: 8px;
    overflow: hidden;
    
    :deep(.el-table__header) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      
      th {
        background: transparent;
        color: white;
        font-weight: bold;
        border-bottom: 1px solid rgba(255, 255, 255, 0.2) !important;
      }
    }
    
    :deep(.el-table__body) {
      td {
        padding: 6px 0;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
      }
      
      tr:hover > td {
        background-color: rgba(102, 126, 234, 0.1) !important;
      }
    }
    
    :deep(.el-table__border-line) {
      border-color: rgba(0, 0, 0, 0.05) !important;
    }
    
    :deep(.el-table--border) {
      border-color: rgba(0, 0, 0, 0.05) !important;
    }
    
    // 修改合计行样式，使其与普通行一致
    :deep(.el-table__footer-wrapper) {
      .el-table__footer {
        background: transparent !important;
        
        td {
          background: transparent !important;
          color: rgba(255, 255, 255, 0.8) !important;
          border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
          border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
          font-weight: bold;
        }
      }
    }
  }
  
  .table-footer {
    margin-top: 10px;
    text-align: right;
    padding: 0 10px;
    
    .total-count {
      color: rgba(255, 255, 255, 0.8);
      font-size: 13px;
      font-weight: normal;
    }
  }
}

.chart-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>

<style lang="scss">
// 全局样式，确保弹框内的下拉选择器和日期选择器弹出层正确显示
.report-dialog {
  .el-select-dropdown {
    z-index: 10000 !important;
  }
  
  .el-picker-panel {
    z-index: 10000 !important;
  }
  
  .el-date-range-picker {
    z-index: 10000 !important;
  }
  
  .el-time-panel {
    z-index: 10000 !important;
  }
}
</style> 